<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2018/5/3
 * Time: 14:06
 */
namespace app\first\model;

use think\Model;

class Article extends Model{
    protected $autoWriteTimestamp = true;
    /**
     * @param array $where
     * @param string $order
     * @param int $limit
     * @param string $filed
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($where=[],$order='create_time desc',$limit=10,$filed='*'){
        $list = $this
            ->field($filed)
            ->with(['user'=>function($query){
                $query->field('id,username,nickname,sex,head,information,hobbies');
            },'cate'=>function($query){
                $query->field('id,title');
            }])
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $collection = new Collection();
        $message = new Message();
        foreach ($list as $k => $v){
            $list[$k]['message'] = $message->where('aid','eq',$v['id'])->count();
            $list[$k]['collection'] = $collection->where('aid','eq',$v['id'])->count();
        }
        return $list;
    }

    /**
     * @param int $id
     * @return array|\PDOStatement|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOneById($id=0){
        $info = $this->find($id);
        $info->hits = $info['hits'] + 1;
        $info->save();
        $res = $this
            ->with(['user'=>function($query){
                $query->field('id,username,nickname,sex,head,information,hobbies');
            },'cate'=>function($query){
                $query->field('id,title');
            }])
            ->where('id','eq',$id)
            ->find();
        $collection = new Collection();
        $message = new Message();
        $res['message'] = $message->where('aid','eq',$res['id'])->count();
        $res['collection'] = $collection->where('aid','eq',$res['id'])->count();
        return $res;
    }
    public function user(){
        return $this
            ->hasOne('member','id','mid');
    }

    public function cate(){
        return $this
            ->hasOne('column','id','cid');
    }
}